/**
 * Created by zyy on 15/9/8.
 * zhangyuyu@superjia.com
 */
(function($) {
    'use strict';
    var smallnote = App.common.smallnote;

    var api = {

        api: function(key) {
            var rootPath = '/api/api';
            return rootPath + {
                list: '',
                create: '/create',
                remove: '/remove'
            }[key];
        },

        collection: new(Backbone.Collection.extend({
            model: Backbone.Model,
            parse: function(response, xhr) {
                if (response.code != 200) {
                    return [];
                }
                var items = response.data;
                if (!items) return response;
                return items;
            }
        })),

        init: function(container, options) {
            var self = this;
            self.container = container;
            self.options = options;

            container.html(tpl);

            self.listPanel = container.find('.list');

            self.collection.bind('reset', self.addItems, self);
            self.collection.bind('add', self.addItem, self);
            self.collection.bind('remove', self.removeItem, self);

            self.events();

        },

        load: function(prdId, callback) {
            var self = this;
            var container = self.container;
            var options = self.options;

            self.prdId = prdId;

            if (options.prd) {
                //如果有prd数据
                var url = location.protocol + '//' + location.host + '/api/debug/' + options.prd.uuid;
                container.find('.api-url').text(url);
            }

            self.listPanel.empty();

            self.collection.fetch({
                url: self.api('list'),
                data: {
                    prdId: prdId
                },
                method: 'get',
                success: function(collection, response, opt) {
                    if (options.apiId) {
                        self.selectItem(options.apiId);
                    }
                },
                error: function() {
                    callback && callback(null)
                }
            })
        },

        events: function() {
            var self = this;
            var container = self.container;

            container.on('click', '.create-btn', function() {
                self.createDialog();
            });
        },

        setOptions: function(options) {
            this.options = $.extend({}, this.options, options);
        },

        initEditor: function(input) {
            var editor_json = CodeMirror.fromTextArea(input, {
                lineNumbers: true,
                mode: "application/json",
                gutters: ["CodeMirror-lint-markers"],
                lint: true
            });
            return editor_json;
        },

        selectItem: function(apiId) {
            var self = this;
            var collection = self.collection;
            if (!apiId) return false;
            collection.where({
                _id: apiId
            })[0].trigger('selected');
        },

        removeItem: function(model, collection, options) {
            var self = this
            model.trigger('remove');
        },

        createDialog: function(apiModel) {
            var self = this;
            var data = apiModel ? apiModel.toJSON() : {
                method: 'get',
                input: JSON.stringify({
                    "name": "api"
                }, null, 4),
                output: JSON.stringify({
                    "status": 1,
                    "data": {
                        "test": "test"
                    }
                }, null, 4),

            };
            var dialog = self.createdialog = new App.common.Dialog({
                width: 600,
                isFixed: false,
                title: '创建api',
                isConfirm: true,
                message: template.draw(createTpl, data),
                okCallback: function() {
                    var descInput = dialog.find('input[name="desc"]');
                    var desc = $.trim(descInput.val());
                    var urlInput = dialog.find('input[name="url"]');
                    var url = $.trim(urlInput.val());
                    var methodInput = dialog.find('input[name="method"]');
                    var method = $.trim(methodInput.val());
                    var input = $.trim(inputEditor.getValue());
                    var output = $.trim(outputEditor.getValue());
                    var commentInput = dialog.find('textarea[name="comment"]');
                    var comment = $.trim(commentInput.val());
                    if (!self.isJson(input)) {
                        smallnote('input不是Json', {
                            pattern: 'error'
                        });
                        return false;
                    }

                    if (!self.isJson(output)) {
                        smallnote('output不是json', {
                            pattern: 'error'
                        });
                        return false;
                    }
                    if (url) {
                        var data = {
                            prdId: self.prdId,
                            desc: desc,
                            url: url,
                            method: method,
                            input: input,
                            output: output,
                            comment: comment
                        };

                        if(apiModel) {
                            data._id = apiModel.toJSON()._id;
                            data.isUpdate = true;
                        }

                        self.createApi(data, function(data) {
                            if(apiModel){
                                apiModel.set(data);
                            }else{
                                self.collection.add([data]);
                            }
                        });
                    }
                }
            });
            var inputEditor = self.initEditor(dialog.find('textarea[name="input"]')[0]);
            var outputEditor = self.initEditor(dialog.find('textarea[name="output"]')[0]);
        },

        isJson: function(str) {
            try {
                JSON.parse(str);
                return true;
            } catch (e) {
                return false;
            }
        },

        createApi: function(api, callback) {
            var self = this;
            $.ajax({
                url: self.api('create'),
                type: 'post',
                data: api,
                success: function(res) {
                    if (res.code == 200) {
                        callback && callback(res.data);
                    }
                }
            });
        },

        removeApi: function(api) {
            var self = this;
            $.ajax({
                url: self.api('remove'),
                data: {
                    _id: api.toJSON()._id
                },
                success: function(res){
                    self.collection.remove(api);
                }
            });
        },

        addItems: function(collection, options) {
            var self = this
            collection.each(function(model) {
                self.addItem(model, collection)
            });
        },

        addItem: function(model, collection, options) {
            var self = this
            var view = new apiView({
                model: model
            })
            self.listPanel.append(view.render().$el);
        }
    };

    var apiView = Backbone.View.extend({
        className: 'api-item',
        tagName: 'ul',
        events: {
            'click': 'itemClick',
            'click .update-btn': 'updateClick',
            'click .remove-btn': 'removeClick'
        },
        initialize: function() {
            var self = this
            self.listenTo(self.model, 'change', self.render);
            self.listenTo(self.model, 'selected', self.selected);
            self.listenTo(self.model, 'remove', self.removeHandler)
        },
        render: function() {
            var self = this
            var data = self.model.toJSON();


            self.$el.html(template.draw(itemTpl, data)).attr('href', '/api/' + data._id);

            return self
        },
        itemClick: function() {
            var self = this;
            var data = null;
            var item = data = self.model.toJSON();

            self.selected();
        },

        updateClick: function() {
            $.jps.trigger('api-update', this.model);
        },

        removeClick: function() {
            var self = this;
            new App.common.deleteDialog({
                okCallback: function() {
                    $.jps.trigger('api-remove', self.model);
                }
            })
        },

        removeHandler: function() {
            this.$el.remove();
        },

        selected: function() {
            this.$el.siblings().removeClass('active').end().addClass('active');
        }
    });

    var tpl = '' +
        '<div class="mod-api">' +
        '    <div class="create-btn btn btn-primary">创建api</div>' +
        '    <div class="api-desc">接口使用地址：<span class="api-url"></span></div>' +
        '    <ul class="api-header">' +
        '        <li class="item-desc">描述</li>' +
        '        <li class="item-url">url</li>' +
        '        <li class="item-method">method</li>' +
        '        <li class="item-input">input</li>' +
        '        <li class="item-output">output</li>' +
        '        <li class="item-comment">备注</li>' +
        '    </ul>' +
        '    <div class="list"></div>' +
        '</div>';

    var createTpl = '' +
        '<div class="api-create">' +
        '    <fieldset class="form-group">' +
        '        <label for="desc">一句话描述</label>' +
        '        <input name="desc" class="form-control" placeholder="一句话描述" value="{{desc}}" />' +
        '    </fieldset>' +
        '    <fieldset class="form-group">' +
        '        <label for="url">url</label>' +
        '        <input name="url" class="form-control" placeholder="url" value="{{url}}" />' +
        '    </fieldset>' +
        '    <fieldset class="form-group">' +
        '        <label for="method">method</label>' +
        '        <input name="method" class="form-control" placeholder="method" value="{{method}}" />' +
        '    </fieldset>' +
        '    <fieldset class="form-group">' +
        '        <label for="input">input，json格式的字符串必须双引号</label>' +
        '        <div class="code-wrap">' +
        '            <textarea name="input" class="form-control" placeholder="input">{{input}}</textarea>' +
        '        </div>' +
        '    </fieldset>' +
        '    <fieldset class="form-group">' +
        '        <label for="output">output，json格式的字符串必须双引号</label>' +
        '        <div class="code-wrap">' +
        '            <textarea name="output" class="form-control" placeholder="output">{{output}}</textarea>' +
        '        </div>' +
        '    </fieldset>' +
        '    <fieldset class="form-group">' +
        '        <label for="comment">comment</label>' +
        '        <textarea name="comment" class="form-control" placeholder="备注">{{comment}}</textarea>' +
        '    </fieldset>' +
        '</div>';

    var itemTpl = '' +
        '<li class="item-desc" title="{{desc}}">{{desc}}</li>' +
        '<li class="item-url" title="{{url}}">{{url}}</li>' +
        '<li class="item-method" title="{{method}}">{{method}}</li>' +
        '<li class="item-input" title="{{input}}">{{input}}</li>' +
        '<li class="item-output" title="{{output}}">{{output}}</li>' +
        '<li class="item-comment" title="{{comment}}">{{comment}}</li>' +
        '<li class="item-opt">' +
        '   <span class="update-btn btn btn-primary btn-sm">更新</span>' +
        '   <span class="remove-btn btn btn-danger btn-sm">删除</span>' +
        '</li>';

    App.modules.api = api;
})(jQuery);
